package rpg.core
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	import rpg.Utils.GameUtils;
	import rpg.Utils.Val;
	import rpg.manager.GameManager;
	import rpg.render.RenderData;
	import rpg.role.Hero;
	import rpg.role.SceneObject;

	public class HpComponent extends RenderComponent
	{
		private var hpBmd : BitmapData;
		private var gm : GameManager;
		private var hero : Hero;

		private var oldMaxHP : int;
		private var oldCurrHP : int;

		private var point : Point;
		private var rectangle : Rectangle;

		public function HpComponent(type : *)
		{
			super(type);
		}

		override public function notifyAdded() : void
		{
			super.notifyAdded();
			hero = owner as Hero;
			render.zIndex = Val.TOP;
			gm = GameManager.getInstance();
			hpBmd = new BitmapData(gm.hpBarBgImg.width , gm.hpBarBgImg.height , true , 0);
			render.bitmapData = hpBmd;

			point = new Point();
			rectangle = new Rectangle();
			oldMaxHP = -1;
			oldCurrHP = -1;
		}

		override public function updateRender(sceneX : int , sceneY : int , offsetX : int = 0 , offsetY : int = 0) : void
		{
			render.x = sceneX - hpBmd.width / 2 - offsetX;
			render.y = sceneY - offsetY - sceneObj.height;
			if(oldMaxHP == hero.data.maxHP && oldCurrHP == hero.data.currHP)
				return;
			oldMaxHP = hero.data.maxHP;
			oldCurrHP = hero.data.currHP;
			var hpWidthPercent : Number = oldCurrHP / oldMaxHP;
			if(hpWidthPercent > 1)
				hpWidthPercent = 1;

			hpBmd.fillRect(hpBmd.rect , 0);
			point.x = 0;
			point.y = 0;
			hpBmd.copyPixels(gm.hpBarBgImg , gm.hpBarBgImg.rect , point , null , null , true);
			point.y = 1;
			rectangle.height = hpBmd.height;
			rectangle.width = hpBmd.width * hpWidthPercent;
			hpBmd.copyPixels(gm.hpBarImg , rectangle , point , null , null , true);
		}
	}
}